#!/usr/bin/env python

from Tkinter import *

class App:
  def clear(self):
    self.prompt.configure(background="white")
    self.prompt.delete(0, END)
    self.resGiven = 1
    self.prompt.insert(0,"0")
    
  def calculate(self):
    try:
      string = str(eval(self.prompt.get()))
      self.prompt.delete(0, END)
      self.prompt.insert(0,string)
      self.resGiven = 1
    except:
      #string of the prompt can't be interpreted
      self.resGiven = 1
      self.prompt.configure(background="red")
    
  def addstring(self, var):
    if self.resGiven == 1:
      self.prompt.delete(0, END)
      self.resGiven = 0
      self.prompt.configure(background="white")
    l = len(self.prompt.get())
    self.prompt.insert(l,var) 
      
  def __init__(self, master):
    #init main frame
    frame = Frame(master)
    frame.grid(row=0, column=0)
    self.resGiven = 0
  
    #init widgets
    self.prompt = Entry(frame, justify=RIGHT, width=30)
    self.prompt.insert(0,"0")
    self.resGiven = 1
    listButton = []
    #number from 9 to 1
    for i in range(1,10):
      listButton.append(Button(frame, width=10, text=i, command = lambda x=i:self.addstring(x)))
    #button number 0
    bt0 = Button(frame, text=0, width=10, command = lambda x=0:self.addstring(x))
    #Enter button
    btCalculate = Button(frame, text="=", width=10,  command = self.calculate)
    btAdd = Button(frame, text="+", width=10, command = lambda x="+":self.addstring(x))
    btMinus = Button(frame, text="-", width=10, command = lambda x="-":self.addstring(x))
    btMult = Button(frame, text="*", width=10, command = lambda x="*":self.addstring(x))
    btDiv = Button(frame, text="/", width=10, command = lambda x="/":self.addstring(x))
    btExp = Button(frame, text="^", width=10, command = lambda x="**":self.addstring(x))
    #clear button
    btClr = Button(frame, text="C", width=10, command = self.clear, justify=CENTER)
    
    
    #Layout
    self.prompt.grid(row=0, column=0, columnspan=2, sticky="W")
    btClr.grid(row=0, column=2)
    row=1
    for i in range(8,-1,-1):
      listButton[i].grid(row=row, column=i%3, padx=5, pady=2)
      if i % 3 == 0:
        row = row + 1
    bt0.grid(row=4, column=0)
    btCalculate.grid(row=4, column=1)
    btAdd.grid(row=1, column=3)
    btMinus.grid(row=2, column=3)
    btMult.grid(row=3, column=3)
    btDiv.grid(row=4, column=3)
    btExp.grid(row=4, column=2)

    



if __name__ == '__main__': 
  root = Tk()
  app = App(root)
  root.title("Calculator")
  root.mainloop()
